<?php
namespace App\Models\ES;

use Elasticsearch\Common\Exceptions\Missing404Exception;
use Elasticsearch\ClientBuilder;

class ElasticBase
{
    static $client;

	public  function __construct()
	{
		if(!isset(self::$client))
        {
        	$host = getenv("ELASTICSEARCH_HOST");
	        $port = getenv("ELASTICSEARCH_PORT");

	        self::$client = $client = ClientBuilder::create()->setHosts([$host . ':' . $port])->build();
        }
	}

	// search
	public function search($params = [] , $size = 10, $from = 0)
    {
    	$table = $this->table();
        $p = [
            'index'   => $table['index'],
            'type'    => $table['type'],
            'routing' => $table['routing'],
            'body'    => $params,
            'size'    => $size,
            'from'    => $from,
        ];
        $s = self::$client->search($p);

        $res = [];
        if (!empty($s['hits'])) {
            $res = $s['hits'];
            return $res;
        }
        return $res;
    }

    public function count($params)
    {
    	$table = $this->table();
        $params = [
            'index' => $table['index'],
            'type'  => $table['type'],
            'body'  => $params,
        ];
        $s = self::$client->count($params);
        if (!empty($s['count'])) {
            return $s['count'];
        }

        return 0;
    }

	// add data
	public function index($params = [])
    {
    	$index  = $this->table();
    	$params = $params ? $params : $this->body();
        $index['id'] = $params['uid'];
        $index['body'] = $params;
        if (!empty($index)) {
            $s = self::$client->index($index);
            if (!empty($s['_shards']['successful'])) {
                return $s;
            }
        }

        return [];
    }

    /*
     * 创建索引
     * */
    public function create_index($index)
    {
        if (!empty($index)) {
            $s = self::$client->index($index);
            if (!empty($s['_shards']['successful'])) {
                return $s;
            }
        }

        return [];
    }

    // create db and table
    public function create($arr = [])
    {
    	$table  = $this->table();
    	$s = $this->exists($table['index']);

        if (!empty($s)) {
            $this->del_index($table['index']);
        }

    	$params = [
                'index' => $table['index'],  //索引名（相当于mysql的数据库）
                'body' => [
                    'mappings' => [
                        $table['type'] => [ //类型名（相当于mysql的表）
                            '_all'=>[   //  是否开启所有字段的检索
                                'enabled' => 'false'
                            ],
                        ]
                    ]
                ]
            ];

       	$params['body']["mappings"][$table['type']]['properties'] = $arr;
       
        $data = self::$client->indices()->create($params);
        print_r($data);
    }

    // delete db and table
    public function del_index($index)
    {
        $s = self::$client->indices()->delete(['index' => $index ]);
    }

    // 
    public function exists($index)
    {
        $s = self::$client->indices()->exists(['index' => $index ]);

        return $s;
    }

    public function getByFid($field,$id)
    {
        $params ['query']['match'][$field] = (int)$id;
        // print_r($params);exit();
        $s = [];
        try {
            $s = $this->search($params,1);
        } catch (Missing404Exception $e) {
          
        }
        return $s;
    }
}